package com.rambo.sdh.common.controller;

import com.google.common.collect.Lists;
import com.rambo.sdh.common.service.inter.GenCodeService;
import com.rambo.sdh.common.service.inter.vo.GenCodeTemplateVO;
import com.rambo.sdh.common.service.inter.vo.GenCodeVO;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by Rambo on 2017/6/12
 **/
@Controller
@RequestMapping("/gencode")
public class GenCodeController extends BaseController {

    private final GenCodeService genCodeService;

    @Autowired
    public GenCodeController(GenCodeService genCodeService) {
        this.genCodeService = genCodeService;
    }


    @RequestMapping("/index")
    public String gencodeIndex() {

        return "common/gencode";
    }


    @PostMapping(value = "/genpo")
    public String gencodePo(@Valid GenCodeVO genCodeVO, BindingResult result, ModelMap modelMap) {
        if (result.hasErrors()) {
            modelMap.addAttribute("msg", result.getAllErrors());
            return "common/gencode";
        }

        Map<String, String> model = new HashMap<>();
        model.put("packageName", genCodeVO.getPackageName().replace(".", File.separator));
        model.put("moduleName", genCodeVO.getModuleName());
        model.put("dBTableNamePO", genCodeVO.getPoName());
        model.put("dBTableName", StrUtil.sub(genCodeVO.getPoName(), 0, genCodeVO.getPoName().indexOf("PO")));
        model.put("lowercaseDBTableNamePO", StrUtil.lowerFirst(genCodeVO.getPoName()));

        ArrayList<String> templateNameList = Lists.newArrayList("dao.xml", "daoimpl.xml");
        List<GenCodeTemplateVO> templateVOList = genCodeService.listGenCodeTemplateVO(templateNameList, model);

        if (CollectionUtil.isNotEmpty(templateVOList)) {
            modelMap.addAttribute("msg", genCodeService.writeFile(templateVOList));
        }
        return "common/gencode";
    }
}